// store/user.js
import { defineStore } from 'pinia';
import { ref, computed } from 'vue';

export const useUserStore = defineStore('user', () => {
  // 用户信息状态
  const userInfo = ref(null);
  // 登录状态
  const isLoggedIn = computed(() => !!userInfo.value);

  // 初始化用户信息（从localStorage加载）
  const initUser = () => {
    const savedUser = localStorage.getItem('userInfo');
    if (savedUser) {
      userInfo.value = JSON.parse(savedUser);
    }
  };

  // 登录成功后设置用户信息
  const setUserInfo = (userData) => {
    userInfo.value = {
      studentId: userData.studentId,
      name: userData.name,
      role: userData.role,
      username: userData.username,
      dormBuilding: userData.dormBuilding,
      dormRoom: userData.dormRoom,
    };
    // 同时保存到localStorage，确保刷新页面后数据不丢失
    localStorage.setItem('userInfo', JSON.stringify(userInfo.value));
  };

  // 登出操作
  const logout = () => {
    userInfo.value = null;
    localStorage.removeItem('userInfo');
  };

  return {
    userInfo,
    isLoggedIn,
    initUser,
    setUserInfo,
    logout,
  };
});    